package com.github.wxiaoqi.security.auth.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.auth.configuration.UserConfiguration;
import com.github.wxiaoqi.security.auth.util.user.JwtTokenUtil;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;

/**
 * Created by ace on 2017/9/10.
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
	/*
	 * private Logger logger =
	 * LoggerFactory.getLogger(UserAuthRestInterceptor.class);
	 */
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private UserConfiguration userConfiguration;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/* HandlerMethod handlerMethod = (HandlerMethod) handler; */
		String token = request.getHeader(userConfiguration.getUserTokenHeader());
		IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
		BaseContextHandler.setUsername(infoFromToken.getUniqueName());
		BaseContextHandler.setName(infoFromToken.getName());
		BaseContextHandler.setUserID(infoFromToken.getId());
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		BaseContextHandler.remove();
		super.afterCompletion(request, response, handler, ex);
	}
}
